package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import io.lettuce.core.GeoArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@Slf4j
public class CacheClient {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private Object r;

    //设置redis缓存
    public void set(String key, Object value, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, timeUnit);
    }

    //设置redis逻辑过期，用于缓存击穿
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit timeUnit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }


    public <R, ID> R queryWithPassThrough(String prefix, ID id, Class<R> type, Function<ID, R> dbFallBack, Long time, TimeUnit timeUnit) {
        String key = prefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        if (json != null) {
            return null;
        }
        R r = dbFallBack.apply(id);

        if (r == null) {
            this.set(key, "", RedisConstants.CACHE_NULL_TTL, timeUnit);
            return null;
        }
        //写入redis
        this.set(key, r, time, timeUnit);

        return r;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    //利用逻辑时间过期，解决缓存击穿问题
    public <R, ID> R queryWithLogicalExpire(String prefix, ID id, Class<R> type, Function<ID, R> dbFallBack, Long time, TimeUnit timeUnit) {
        String cacheKey = prefix + id;
        String shopJson = stringRedisTemplate.opsForValue().get(cacheKey);
        //未命中redis直接返回null
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }
        //命中先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断缓存是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期直接返回
            return r;
        }
        //过期了直接进行缓存重建
        //获取互斥锁
        String lockKey = prefix + id;
        Boolean aBoolean = this.tryLock(lockKey);
        //判断是否获取锁成功
        if (aBoolean) {
            //获取成功，开启线程，执行重建
            try {
                //查询数据库
                R r1 = dbFallBack.apply(id);
                setWithLogicalExpire(cacheKey, r1, time, timeUnit);
            } catch (Exception e) {
                throw new RuntimeException();
            } finally {
                unlock(lockKey);
            }
        }
        return r;
    }

    //获取锁(根据当前操作的类型和店铺id作为key，利用setnx唯一性)
    public Boolean tryLock(String key) {
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    //释放锁
    public void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

}
